package com.houhanzhi.listener;

import com.houhanzhi.enums.BizCodeEnum;
import com.houhanzhi.enums.EventMessageTypeEnum;
import com.houhanzhi.exception.BizException;
import com.houhanzhi.model.EventMessage;
import com.houhanzhi.service.ShortLinkService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
//@RabbitListener(queues = "short_link.add.link.queue")
@RabbitListener(queuesToDeclare = { @Queue("short_link.update.link.queue") })
public class ShortLinkUpdateLinkMQListener {

    @Autowired
    private ShortLinkService shortLinkService;

    /**
     * 处理器
     *
     * @param eventMessage 消息对象
     * @param message 常规对象
     * @param channel 消息通道
     * @throws IOException
     */
    @RabbitHandler
    public void shortLinkHandler(EventMessage eventMessage, Message message, Channel channel) throws IOException {

        log.info("监听到消息ShortLinkUpdateLinkMQListener：message消息内容：{}", message);
        try {
            eventMessage.setEventMessageType(EventMessageTypeEnum.SHORT_LINK_UPDATE_LINK.name());
            shortLinkService.handlerUpdateShortLink(eventMessage);
        } catch (Exception e) {
            // 处理业务失败，还要进行其他操作，比如记录失败原因
            log.error("消费失败{}", eventMessage);
            throw new BizException(BizCodeEnum.MQ_CONSUME_EXCEPTION);
        }
        log.info("消费成功{}", eventMessage);
        // 确认消息消费成功（false: 单个处理）
//        channel.basicAck(msgTag, false);
    }
}
